# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :users.py
# @Time      :2022/6/8 19:39
# @Author    :张志坤

# 创建蓝图
from flask_restful import reqparse, Resource, marshal, current_app, Api
from flask import g, jsonify, Blueprint, request
from common.celery_tasks.send_code import sms_code
from models.user import *
from common.utils.jwt_generate import generate_token
from common.project_fields.user_fields import *
from common.utils.login_xxx import login_request
from models import db
import random
import redis
from common.utils.qiniu_token import qiniu_token

user_bp = Blueprint('user_bp', __name__, url_prefix="/v1_0")
api = Api(user_bp)


# 发送短信验证码
class SmsCode(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('mobile')

        args = parser.parse_args()

        mobile = args['mobile']
        print("手机号", mobile)
        # 生成验证码
        code = "%s" % random.randint(100000, 999999)
        print("生成的验证码", code)
        # 发送验证码
        res = sms_code.delay(mobile, code, expiry=5)
        if res:
            # 发送成功  存到redis
            rds = redis.Redis()
            rds.setex(mobile, 60 * 5, code)
            rds.close()
            return jsonify(msg='发送成功,注意查收!!!', code=200)
        else:
            return jsonify(msg="发送失败", code=400)


# 登陆注册
class LoginRegister(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('mobile')
        parser.add_argument('code')
        args = parser.parse_args()
        mobile = args['mobile']
        code = args['code']
        # 校验验证码
        rds = redis.Redis()
        sms_code = rds.get(mobile)
        if not sms_code:
            # 没获取到
            return jsonify(msg='验证码过期', code=400)
        else:
            # 获取到了
            if code != sms_code.decode():
                # 验证码不正确
                return jsonify(msg='验证码错误', code=400)
            else:
                # 验证码正确
                # 从数据库查询 用户是否存在
                user = UserModel.query.filter_by(mobile=mobile).first()
                # 判断用户是否存在
                if not user:
                    # 没有    添加  注册
                    try:
                        u = UserModel(mobile=mobile)
                        db.session.add(u)
                        db.session.commit()
                    except Exception as e:
                        print("注册失败", e)
                        return jsonify(msg="注册失败", code=400)
                    return jsonify(msg='注册成功', code=201)
                else:
                    token, refresh_token = generate_token(payload={'uid': user.uid, "is_refresh": False})
                    # 有    生成token  登录成功
                    return jsonify(token=token, refresh_token=refresh_token, msg="登陆成功", code=200, id=user.uid)

    def put(self):
        user = UserModel.query.filter_by(uid=g.user_id).first()
        if not user:
            return jsonify("用户不存在", code=400)
        token, refresh_token = generate_token(payload={'uid': g.user_id, "is_refresh": True})
        return jsonify(token=token, refresh_token=refresh_token, msg="刷新token成功", code=200, id=g.user_id)


# 获取所有频道
class ChannelResource(Resource):
    @login_request
    def get(self):
        chas = Channel.query.all()
        if not chas:
            return jsonify(msg="暂无频道", code=400)
        else:
            data = marshal(chas, channel_fields)
            return jsonify(msg='获取成功', code=200, data=data)


# 获取频道下的文章
class CNewSB(Resource):
    @login_request
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('channel_id')
        args = parser.parse_args()
        channel_id = args['channel_id']

        try:
            cha = News.query.filter_by(channel_id=channel_id).all()
            print('获取到的文章', cha)
            if cha:
                chalist = []
                for i in cha:
                    # 给文章加个品论数量的字段
                    reply_count = len(Comment.query.filter_by(article_id=i.nid).all())
                    print("文章的评论>>>>>>>>>>>>>>>>>>>>长度", reply_count)
                    data = marshal(i, news_fields)
                    print(1111)
                    data['reply_count'] = reply_count
                    print(22222)
                    chalist.append(data)
                return jsonify(msg="获取成功", code=200, data=chalist)
            else:
                return jsonify(msg='还没有文章哟!亲', code=400)
        except Exception as e:
            print("频道下文章报错", e)
            return jsonify(msg='报错了!亲', code=400)


# 文章 详情
class NewsDetail(Resource):
    @login_request
    def get(self, nid):
        # 获取文章详情
        new = News.query.filter_by(nid=nid).first()
        if not new:
            return jsonify(msg='暂无该文章', code=200)
        # 获取作者信息
        user = UserModel.query.filter_by(uid=new.user_id).first()
        # # 获取文章的评论
        # comment = new.comment
        # print("评论", comment)

        data = marshal(new, news_fields)
        data['uname'] = user.uname
        data['profile_photo'] = user.profile_photo
        return jsonify(msg="获取成功", code=200, data=data)


# 获取评论
class CommentsResource(Resource):
    @login_request
    def get(self):
        # 获取文章的评论
        parser = reqparse.RequestParser()
        parser.add_argument('source')
        args = parser.parse_args()
        nid = args['source']
        print("文章的id", nid)
        # 获取文章的一级评论
        comment = Comment.query.filter_by(article_id=nid, parent_id=None).all()
        if not comment:
            return jsonify(msg="暂无评论", code=200, data=[])
        # 获取以及评论的用户信息
        list1 = []
        for i in comment:
            user = UserModel.query.filter_by(uid=i.user_id).first()
            # 获取一级品论下的评论数量
            reply_count = len(Comment.query.filter_by(parent_id=i.cmid).all())
            # 对评论数量进行修改
            try:
                Comment.query.filter_by(cmid=i.cmid).update({"reply_count": reply_count})
                db.session.commit()
            except Exception as e:
                print("修改品论数量报错", e)
            c1 = marshal(i, common_fields)
            c1['reply_count'] = reply_count  # 更新响应的评论数量
            if user:
                c1['uname'] = user.uname
                c1['profile_photo'] = user.profile_photo
            # 获取二级评论
            comment2 = Comment.query.filter_by(parent_id=i.cmid).all()
            list2 = []
            if not comment2:
                list2 = None
            else:
                for j in comment2:
                    user = UserModel.query.filter_by(uid=i.user_id).first()
                    c2 = marshal(j, common_fields)
                    c2['uname'] = user.uname
                    c2['profile_photo'] = user.profile_photo
                    list2.append(c2)
            c1['parent'] = list2
            list1.append(c1)
        return jsonify(msg="获取成功", code=200, data=list1)

        # 获取二级评论的用户信息

    @login_request
    def post(self):
        # 添加评论
        parser = reqparse.RequestParser()
        parser.add_argument('target')  # 文章id
        parser.add_argument('content')  # 内容
        parser.add_argument('art_id')  # 评论id
        args = parser.parse_args()
        nid = args['target']  # 文章id
        content = args['content']  # 内容
        cid = args['art_id']  # 被评论id
        print("111111111111111111111111111111111cid", cid, nid)
        if not content:
            # 评论为空
            return jsonify(msg='请输入评论内容', code=400)
        if not all([nid, cid]):
            # 若有为空
            # 判断文章id
            if nid:
                # 文章id存在
                # 添加一级评论
                try:
                    a = Comment(article_id=nid, content=content, user_id=g.user_id)
                    db.session.add(a)
                    db.session.commit()
                except Exception as e:
                    print("存入一级评论爆错", e)
                    return jsonify(msg='发布失败', code=400)
                return jsonify(msg='发布成功', code=200)
        else:
            # 都存在  则是二级评论
            try:
                c = Comment(article_id=nid, content=content, parent_id=cid, user_id=g.user_id)
                db.session.add(c)
                db.session.commit()
            except Exception as e:
                print("存入二级评论报错", e)
                return jsonify(msg='发布失败', code=400)
            return jsonify(msg='发布成功', code=200)


# 获取用户信息
class UserInfo(Resource):
    @login_request
    def get(self):
        user_id = g.user_id
        user = UserModel.query.filter_by(uid=user_id).first()
        if user:
            data = marshal(user, user_fields)
            return jsonify(code=200, msg="获取成功", data=data)
        return jsonify(code=400, msg='获取失败', data={})


# 获取七牛token
class QiniuToken(Resource):
    @login_request
    def get(self):
        token = qiniu_token()
        return token


# 修改图片
class UpdateUserInfo(Resource):
    def patch(self):
        parser = reqparse.RequestParser()
        parser.add_argument('profile_photo')
        parser.add_argument('created_time')
        parser.add_argument('gender')
        parser.add_argument('uname')
        args = parser.parse_args()
        created_time = args['created_time']
        gender = args['gender']
        uname = args['uname']
        profile_photo = args['profile_photo']
        user = UserModel.query.filter_by(uid=g.user_id).first()
        if not user:
            return jsonify(msg='用户不存在', code=200)
        if created_time:
            print('日期', created_time)
            try:
                UserModel.query.filter_by(uid=g.user_id).update({'created_time': created_time})
                db.session.commit()
                return jsonify(msg='修改成功', code=200)
            except Exception as e:
                print('修改日期报错', e)
                return jsonify(msg='修改失败', code=200)
        if gender:
            print('性别', gender)
            try:
                UserModel.query.filter_by(uid=g.user_id).update({'gender': gender})
                db.session.commit()
                return jsonify(msg='修改成功', code=200)
            except Exception as e:
                print('修改性别报错', e)
                return jsonify(msg='修改失败', code=200)
        if uname:
            print('昵称', uname)
            try:
                UserModel.query.filter_by(uid=g.user_id).update({'uname': uname})
                db.session.commit()
                return jsonify(msg='修改成功', code=200)
            except Exception as e:
                print('修改昵称报错', e)
                return jsonify(msg='修改失败', code=200)
        if profile_photo:
            print('头像', profile_photo)
            try:
                UserModel.query.filter_by(uid=g.user_id).update({'profile_photo': profile_photo})
                db.session.commit()
                return jsonify(msg='修改成功', code=200)
            except Exception as e:
                print('修改头像报错', e)
                return jsonify(msg='修改失败', code=200)


api.add_resource(SmsCode, '/sms_code')
api.add_resource(LoginRegister, '/authorizations')
api.add_resource(ChannelResource, '/channels')
api.add_resource(CNewSB, '/articles')
api.add_resource(NewsDetail, '/articles/<int:nid>')
api.add_resource(CommentsResource, '/comments')
api.add_resource(UserInfo, '/user/profile')
api.add_resource(QiniuToken, '/qiniu')
api.add_resource(UpdateUserInfo, '/user/profile')
